﻿using System;
using System.Data;

namespace DMirrorMySQL
{
    public class Util
    {
        public static string ToTimeStamp(DateTime dtNow)
        {
            DateTime dtStart = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));
            // DateTime dtNow = DateTime.Parse(DateTime.Now.ToString());
            TimeSpan toNow = dtNow.Subtract(dtStart);
            string timeStamp = toNow.Ticks.ToString();
            timeStamp = timeStamp.Substring(0, timeStamp.Length - 7);
            return timeStamp;
        }

        public static DateTime ToDateTime(string timeStamp)
        {
            //string timeStamp = "1176686120";
            DateTime dtStart = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));
            long lTime = long.Parse(timeStamp + "0000000");
            TimeSpan toNow = new TimeSpan(lTime);
            DateTime dtResult = dtStart.Add(toNow);
            return dtResult;
        }

        /// <summary>
        /// 将数据行转换为DPost格式
        /// </summary>
        /// <param name="r">引用数据行,应与数据库中的posts表中数据格式相同</param>
        /// <param name="d">引用DPost对象</param>
        public static void fillRowToDPost(ref DataRow r, ref DPost d)
        {
            int.TryParse(r["post_id"].ToString(), out d.PostID);
            int.TryParse(r["site_id"].ToString(), out d.SiteID);
            int.TryParse(r["width"].ToString(), out d.Width);
            int.TryParse(r["height"].ToString(), out d.Height);
            int.TryParse(r["status"].ToString(), out d.Status);
            int.TryParse(r["iphoto_id"].ToString(), out d.iPhotoID);
            d.MD5 = r["md5"].ToString();
            d.PATH = r["path_photo"].ToString();
            d.tPATH = r["path_thumb"].ToString();
            d.URL = r["url"].ToString();
            d.tURL = r["url_thumb"].ToString();
            d.Modified = Util.ToDateTime(r["modified"].ToString());
        }

        public static DPost dataRowToPost(ref DataRow r)
        {
            DPost d = new DPost();
            int.TryParse(r["post_id"].ToString(), out d.PostID);
            int.TryParse(r["site_id"].ToString(), out d.SiteID);
            int.TryParse(r["width"].ToString(), out d.Width);
            int.TryParse(r["height"].ToString(), out d.Height);
            int.TryParse(r["status"].ToString(), out d.Status);
            int.TryParse(r["iphoto_id"].ToString(), out d.iPhotoID);
            d.MD5 = r["md5"].ToString();
            d.PATH = r["path_photo"].ToString();
            d.tPATH = r["path_thumb"].ToString();
            d.URL = r["url"].ToString();
            d.tURL = r["url_thumb"].ToString();
            d.Modified = Util.ToDateTime(r["modified"].ToString());
            return d;
        }
    }
}